/*
 * Copyright (C) 2008  Wang Hoi <fearee@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  US
*/
#include "file_source.h"
FileSource::FileSource(const QByteArray &apath): file_info(apath), pos(0)
{
}
FileSource::~FileSource()
{
}
void FileSource::init()
{
    watcher.addPath(file_info.path());
    file.setFileName(file_info.filePath());
    if (file.exists())
        watcher.addPath(file_info.filePath());
    connect(&watcher, SIGNAL(fileChanged(const QString&)),
            SLOT(onFileChanged(const QString&)), Qt::QueuedConnection);
    connect(&watcher, SIGNAL(directoryChanged(const QString&)),
            SLOT(onDirectoryChanged(const QString&)), Qt::QueuedConnection);
    update();
}
void FileSource::update()
{
    if (!file.exists())
        return;
    qint64 new_pos = 0;
    new_pos = file.size();
    if (new_pos > pos) {
        file.open(QIODevice::ReadOnly);
        file.seek(pos);
        buf = file.read(new_pos - pos);
        pos = new_pos;
        file.close();
        emit dataGot(buf);
    }
}
void FileSource::onFileChanged(const QString &path)
{
    update();
}

void FileSource::onDirectoryChanged(const QString &path)
{
    if (file.exists()) {
        if (!watcher.files().contains(file_info.filePath())) {
            watcher.addPath(file_info.filePath());
            update();
        }
    } else {
        if (watcher.files().contains(file_info.filePath())) {
            watcher.removePath(file_info.filePath());
        }
    }
}

#include "file_source.moc"
